<?php 
namespace app\App\controller;

use app\App\validate\DeviceMessageValidate;
use app\App\model\DeviceMessageModel;
use Exception;
use plugin\saiadmin\basic\AppBaseController;
use think\facade\Db;
use support\Log;
use support\Request;
use support\Response;


// APP设备消息模块
class DeviceMessageController extends AppBaseController{

    public function __construct()
    {
        $this->bareModel = new DeviceMessageModel();
        $this->validate = new DeviceMessageValidate();
        parent::__construct();
    }


    // 用户设备消息列表
    public function messageList($request){
        // 自连接查询自己，获取最近的时间的消息
        $msgList = $this->bareModel->alias('msg')
        ->join('(select device_id, max(id) as id from ski_device_msg_list group by device_id) as msg_self', 'msg_self.id=msg.id')
        ->join('ski_device_list device', 'msg.device_id = device.device_id', 'LEFT')
        ->where('device.user_id', $this->userId)->field('msg.id, msg.device_id,  msg.title, msg.desc, msg.content, msg.create_time, msg.has_read')
        ->select()->toArray();
        
        // @debug 调试，打印SQL日志
        // printSQL($this->bareModel->alias('msg')
        // ->join('(select device_id, max(id) as id from ski_device_msg_list group by device_id) as msg_self', 'msg_self.id=msg.id')
        // ->join('ski_device_list device', 'msg.device_id = device.device_id', 'LEFT')
        // ->where('device.user_id', $this->userId)->field('msg.*'));

        return $this->success($msgList);
    }


    // 删除消息记录
    public function deleteMsg($request){
        $msg_ids = $request->post('ids',[]);
        if(!is_array($msg_ids)){
            return $this->fail(trans('common.param_error'));
        }
        $ids = convertToNumbersArr($msg_ids);
        if(count($ids)==0){
            return $this->fail(trans('common.param_error'));
        }

        // @Note thinkOrm 连接删除有问题
        // $delSQL = $resultFlag = $this->bareModel->alias('msg')
        //     ->join('ski_device_list device', 'msg.device_id = device.device_id', 'LEFT')
        //     ->where('device.user_id', $this->userId)->where('msg.id', 'in', $ids);
        // $resultFlag = $delSQL->delete('msg');
        
        /*  创建一个填充了和params相同数量占位符的字符串 */
        $place_holders = implode(',', array_fill(0, count($ids), '?'));
        // @Note：连接删除，参数数组, 需要创建多个占位符
        $delSQL = "DELETE `msg` FROM `ski_device_msg_list` `msg` 
                LEFT JOIN `ski_device_list` `device` ON `msg`.`device_id`=`device`.`device_id` 
                WHERE  `device`.`user_id` = ?  AND `msg`.`id` IN ($place_holders)";

        // 执行 SQL 并传入参数数组
        $resultFlag = Db::execute($delSQL, array_merge([ $this->userId ], $ids));

        if(isFalse($resultFlag)){
            return $this->fail(trans('common.fail'));
        }
        return $this->success(trans('common.success'));
    }

    // 获取设备消息-分页
    public function getListofDevice($request){
        if(!$this->validate->scene('list')->check($request->get())){
             return $this->fail($this->validate->getError());
        }

        $pageNum = $request->get('pageNum', 1);
        $pageSize = $request->get('pageSize', 10);
        $device_id = $request->get('device_id', '');

        // 这里加上 user_id的连接是为做数据隔离，防止查到其他人的数据
        $msgList = $this->bareModel->alias('msg')
            ->join('ski_device_list device', 'msg.device_id = device.device_id', 'LEFT')
            ->where('device.user_id', $this->userId)
            ->where('msg.device_id', $device_id)
            ->field('msg.id, msg.device_id,  msg.title, msg.desc, msg.content, msg.create_time, msg.has_read')
            ->paginate([ 'list_rows' => $pageSize,'page' => $pageNum],false)->toArray(); // false-为默认非简洁模式，true-简洁模式（没有total字段）

        return $this->success( $msgList );
    }

}